﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer;
using DataAccessLayer;
using MyException;

namespace PresentationLayer
{
    public partial class Login1 : System.Web.UI.Page
    {
        LoginToSystemControl control;

        protected void Page_Load(object sender, EventArgs e)
        {
            control = new LoginToSystemControl();

            if (!IsPostBack)
            {
                Session.Remove("UserLoggedIn");
                if (Request.Cookies["UsersRole"] != null)
                {
                    HttpCookie roleCookie = new HttpCookie("UsersRole");
                    roleCookie.Expires = DateTime.Now.AddDays(-1d);
                    Response.Cookies.Add(roleCookie);
                }
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string username = txtUsername.Value.Trim().ToString();
            string password = txtPassword.Value.Trim().ToString();

            try
            {
                if (username.Equals("") || password.Equals(""))
                {
                    throw new InvalidUserException();
                }

                // Validate username and password
                List<string> list = control.ValidateUserByUsernameAndPassword(username, password);
                string result = list[0];
                string redirectURL = list[1];

                if (result.Equals("validuser"))
                {
                    // Create Session and Cookie
                    Session["UserLoggedIn"] = list;
                    string roleId = list[6];
                    HttpCookie roleCookie = new HttpCookie("UsersRole");
                    roleCookie.Values.Add("roleId", roleId);
                    Response.Cookies.Add(roleCookie);
                    Response.Redirect(redirectURL);
                }
                else
                {
                    throw new InvalidUserException();
                }
            }
            catch (InvalidUserException ex)
            {
                lblError.Text = "* Please enter a valid username and password";
            }
        }
    }
}